import ajax from "../api/ajax";

class Paging {

    page
    limit
    req
    locker = false
    url
    moreData = true
    accumulator = []


    constructor(req, page = 1, limit = 10) {
        this.page = page
        this.limit = limit
        this.req = req
        this.url = req.url
    }

    async getMoreData() {
        if(!this.moreData){
            return
        }
        if(!this._getLocker()){
            return
        }
        const data =await this._actualGetData()
        this._releaseLocker()
        return data
    }


    async _actualGetData() {
        const req = this._getCurrentReq()
        let paging = await ajax(req.url, req.params,'GET')
        const res = paging.data
        if(!res){
            return null
        }
        if(res.page_info.total === 0){
            return {
                empty:true,
                items:[],
                moreData:false,
                accumulator:[]
            }
        }

        this.moreData = Paging._moreData(this.accumulator.length, res.page_info.total)
        if(this.moreData){
            this.page ++
        }
        this._accumulate(res.data)
        return {
            empty:false,
            items: res.data,
            moreData:this.moreData,
            accumulator:this.accumulator
        }
    }

    _accumulate(items){
        this.accumulator = this.accumulator.concat(items)
    }

    static _moreData(currentCount,total) {
        return currentCount < total
    }

    _getCurrentReq() {
        let url = this.url
        /*const params = `page=${this.page}&limit=${this.limit}`*/
        const params = {
            page: this.page,
            limit: this.limit
        }
        /*if(url.includes('?')){
            url += '&' + params
            // contains
        }
        else{
            url += '?' + params
        }*/
        this.req.url  = url
        this.req.params = params
        return this.req
    }

    _getLocker() {
        if (this.locker) {
            return false
        }
        this.locker = true
        return true
    }

    _releaseLocker() {
        this.locker = false
    }

}

export {
    Paging
}
